package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;

    /**
     * 1.创建bucket
     * 2.设定自定义策略
     * 3.准备object对象
     *      3.1 IO资源 putObject
     *      3.2 解决重名问题  使用uuid
     *      3.3 选做 分目录存储 jpg png  jepg   | hash分组 | 时间方式存储yyyy/MM/
     */
    @Override
    public String upload(MultipartFile file) {
        //1.创建bucket
        createBucket();

        //2.上传文件
        String fileName = putObject(file);

        //返回系统访问的URL地址
        //http://192.168.126.128:9000/lease/2024/07/uuid.jpg
        return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + fileName;
    }

    public String  putObject(MultipartFile file){
        //2.上传文件
        String bucketName = minioProperties.getBucketName();

        //3.解决重名问题
        String uuid = UUID.randomUUID().toString().replace("-","");
        //4.截取文件的后缀类型     获取文件名称  abc.jpg  ---> .jpg
        String fileName = file.getOriginalFilename();
        //5.生成时间目录
        String dirPath = new SimpleDateFormat("/yyyy/MM/").format(new Date());
        fileName = dirPath + uuid + fileName.substring(fileName.lastIndexOf("."));

        //6.指定文件类型   image/jpeg
        String contentType = file.getContentType();

        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .contentType(contentType)
                    .stream(file.getInputStream(),file.getSize(),-1).build();
            minioClient.putObject(putObjectArgs);
        }catch (Exception e){
            //e.printStackTrace();
            throw new RuntimeException(e);
        }

        return fileName;
    }

    public void createBucket(){
        try {
            String bucketName = minioProperties.getBucketName();
            if(!    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())){
                //创建bucket
                MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
                minioClient.makeBucket(makeBucketArgs);
                //设定自定义策略
                String config =
                        """
                         {
                                   "Statement" : [ {
                                     "Action" : "s3:GetObject",
                                     "Effect" : "Allow",
                                     "Principal" : "*",
                                     "Resource" : "arn:aws:s3:::%s/*"
                                   } ],
                                   "Version" : "2012-10-17"
                                 }
                        """.formatted(bucketName);
                SetBucketPolicyArgs setBucketPolicyArgs =
                        SetBucketPolicyArgs.builder().bucket(bucketName).config(config).build();
                minioClient.setBucketPolicy(setBucketPolicyArgs);
            }
        } catch (Exception e) {
            //e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
